<script setup lang='ts'>
import {ref, reactive, PropType, onBeforeMount} from 'vue'
import {FormRules, ElMessage} from 'element-plus'
import {FromItem} from '@/components/dFrom/dFrom'
import {SignFormInfor, saveSignInfor, SignDetailInfor, getDictionaries, editSignInfor} from '@/api/baseSetting/labSign'
import {DialogType} from '@/api/config'
import dDialog from '@/components/dDialog/dDialog.vue'
import dFrom from '@/components/dFrom/dFrom.vue'
import type { UploadProps, UploadUserFile } from 'element-plus'
import {SeleteData} from '@/api/config'
// import {useStore} from '@/store/index'
import useUser from '@/store/user'
import {transfDicArrData, getObjectByKey, transfArrData} from '@/util/common'
//是否显示
const props = defineProps({
  //显示
  showDialog:{
    type:Boolean,
    required:true
  },
  //弹窗类型
  dialogType:{
    type:String as PropType<DialogType>,
    required:true
  },
  //数据
  signData:{
    type:Object as PropType<SignFormInfor>,
    required:true
  }
})

// const store = useStore()

const emits = defineEmits(['close'])

// 弹窗标题定义
const title = ref('')

// 弹窗标题设置
const initTitle = () => {
  if (props.dialogType === 'add') {
    title.value = '新增书籍'
  }
  else if (props.dialogType === 'edit') {
    title.value = '编辑书籍'
  }
}

//信息
const fromData:SignFormInfor = reactive(props.signData)

// 显示加载状态
const showSaveLoading = ref(false)

// 表单规则
const rules = reactive<FormRules>({
  categoryId:[
    {required: true, message: '请选择书籍类型', trigger: ['change', 'blur']}
  ],
  author:[
    {required: true, message: '请输入作者', trigger: ['change', 'blur']}
  ],
  name:[
    {required: true, message: '请输入书籍名称', trigger: ['change', 'blur']}
  ],
  price:[
    {required: true, message: '请输入书籍价格', trigger: ['change', 'blur']}
  ]
})

//下拉 类型 语言 抬头 纸张 定义
const sealTypeNameList = ref<Array<SeleteData>>([])

//表单项
const fromItems = ref<Array<FromItem>>([
  {label:'书籍类型', placeholder:'请选择书籍类型', prop:'categoryId', type:'selete', seleteData:sealTypeNameList.value, notClearable:true},
  {label:'书籍作者', placeholder:'请输入书籍作者', prop:'author', type:'input'},
  {label:'书籍名字', placeholder:'请输入书籍名字', prop:'name', type:'input'},
  {label:'书籍价格', placeholder:'请输入书籍价格', prop:'price', type:'input'}


])

//表单清除控制
const resetFieldsFlag = ref(false)

const validateFlag = ref(false)

// 确认按钮
const onConfirm = () => {
  validateFlag.value = !validateFlag.value
}

//关闭
const onClose = () => {
  emits('close')
  //关闭后清除表单数据以及表单验证数据 可根据具体业务自行调整
  resetFieldsFlag.value = !resetFieldsFlag.value
}

//取消按钮
const onCancel = () => {
  onClose()
}

// 上传文件
const fileList = ref<UploadUserFile[]>([])

// 放大图片数据
const dialogImageUrl = ref('')

// 展示放大框
const dialogVisible = ref(false)

//上传图片成功
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  if (response.code === 2000) {
    // console.log('response', response.data)

    fromData.cover = response.data.path
    ElMessage.success('上传成功！')
  } else {
    fileList.value = []
    ElMessage.error('服务器未找到，上传失败！')
  }
}

//删除照片
const handleRemove: UploadProps['onRemove'] = () => {
  fromData.cover = undefined
  ElMessage.success('删除成功！')
}

//上传图片限制
const handleExceed: UploadProps['onExceed'] = () => {
  ElMessage.error('上传失败！当前限制最多选择1张图片，超出图片限制！')
}

//检验上传图片格式
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/jpg') {
    ElMessage.error('格式只支持JPG/JPEG/PNG!')
    return false
  } else if (rawFile.size / 1024 > 500) {
    ElMessage.error('图片大小不能超过 500kb!')
    return false
  }
  return true
}

//编辑时查看照片
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

//上传数据
const uploadData = ref({bucketName:'labsign-img'})

//表单验证通过事件
const onSubmit = () => {
  console.log('fromData.cover', fromData.cover)

  if (!fromData.cover) {
    ElMessage.error('封面图片不能为空！')
    return false
  }
  if (fromData.categoryId) {
    sealTypeNameList.value.forEach((item) => {
      if (item.value === fromData.categoryId) {
        fromData.categoryName = item.label
      }
    })
  }
  showSaveLoading.value = true
  const reportAllInfor:SignDetailInfor = {...({categoryId:fromData.categoryId, categoryName:fromData.categoryName, author:fromData.author, cover:fromData.cover, description:fromData.description, price:fromData.price, id:fromData.id, name:fromData.name} as SignDetailInfor)}
  if (props.dialogType === 'add') {
    saveSignInfor(reportAllInfor).then(() => {
      showSaveLoading.value = false
      ElMessage.success('保存成功！')
      emits('close')
    }).catch((error) => {
      showSaveLoading.value = false
      console.warn(error)
    })
  } else if (props.dialogType === 'edit') {
    editSignInfor(reportAllInfor).then(() => {
      showSaveLoading.value = false
      ElMessage.success('编辑成功！')
      emits('close')
    }).catch((error) => {
      showSaveLoading.value = false
      console.warn(error)
    })
  }

}

onBeforeMount(() => {
  initTitle()
  if (props.dialogType === 'edit')fileList.value.push({name:'', url:fromData.cover})
  getDictionaries().then((res) => {
    // const item = getObjectByKey(fromItems.value, 'prop', 'categoryName')
    // console.log('item', item)
    const dataList = res.data.data as any
    console.log('查出来的数据0', sealTypeNameList.value, res.data.data, dataList)
    const arr:Array<SeleteData> = transfArrData(dataList.list, {'name':'label', 'id':'value'})
    arr.forEach((item) => {
      sealTypeNameList.value.push(item)
    })
    // if (item && item.type === 'selete') {
    //   item.seleteData = transfDicArrData(res)
    // }
  })
  console.log('编辑', fromData)

})

</script>

<template>
  <d-dialog
    custom-class="size"
    :title="title"
    :show-dialog="showDialog"
    :show-save-loading="showSaveLoading"
    @cancel="onCancel"
    @confirm="onConfirm"
    @close="onClose"
  >
    <d-from
      label-position="right"
      :label-width="90"
      :reset-fields-flag="resetFieldsFlag"
      :validate-flag="validateFlag"
      :rules="rules"
      method="post"
      :form-data="fromData"
      :form-items="fromItems"
      :form-line-num="1"
      @submit="onSubmit"
    />
    <div :style="{display:'flex'}">
      <div class="avatar-text">
        <span class="avatar-text-span">*</span>
        封面图片
      </div>
      <div>
        <el-upload
          v-model:file-list="fileList"
          action="/api/uploadImage"
          list-type="picture-card"
          :limit="1"
          :on-success="handleAvatarSuccess"
          :on-exceed="handleExceed"
          :before-upload="beforeAvatarUpload"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :headers="{'Authorization': 'Bearer ' + useUser.setup().store.token as string}"
          name="image"
        >
          <el-icon>
            <Plus />
          </el-icon>
        </el-upload>
        <el-dialog v-model="dialogVisible" width="100">
          <img w-full :src="dialogImageUrl" alt="Preview Image">
        </el-dialog>
        <div class="avatar-info">
          上传说明：
          最多上传1张图片，建议尺寸为260mm x 160mm，格式支持JPG/JPEG/PNG , 大小不超过 500KB;
        </div>
      </div>
    </div>
    <div label-width="100px" :style="{marginTop: '20px',marginBottom: '20px',marginLeft: '46px'}">
      <el-form-item label="书籍描述">
        <el-input v-model="fromData.description" type="textarea" placeholder="请输入书籍描述" maxlength="200" :show-word-limit="true" :autosize="{minRows: 2, maxRows: 6}" />
      </el-form-item>
    </div>
  </d-dialog>
</template>

<style scoped>
.avatar-text {
  width: 112px;
  display: block;
  margin-left:12px;
  margin-top:36px;
  margin-bottom:24px
}
.avatar-text-span {
  color:var(--el-color-danger)
}
.avatar-info {
  color:#999;
  margin-top:17px
}
</style>
<style>
.size  {
  width: 600px;
}
</style>